package cn.limin;

import cn.limin.domain.Pigeon;
import cn.limin.utils.LmFileHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException
                                                ,ClassNotFoundException{

        Scanner sc = new Scanner(System.in);

        while(true){
            welcome();

            Integer opr = sc.nextInt();

            if(opr==4)
                break;

            switchOperation(opr,sc);
        }

        System.out.println("拜拜了老铁,欢迎下次光临!!!");
    }

    private static void switchOperation(Integer opr,Scanner sc)throws IOException
                                                                    , ClassNotFoundException {
        switch (opr){
            case 1:
                show();
                break;
            case 2:
                add(sc);
                break;
            case 3:
                remove(sc);
                break;
            default:
        }
    }

    private static void remove(Scanner sc) throws IOException,ClassNotFoundException  {
        ArrayList<Pigeon> pigeons = LmFileHelper.readPigeons();

        if(pigeons==null || pigeons.isEmpty()){
            System.out.println("展厅空空如也,不能下架!!!");
            return;
        }

        System.out.println("请输入要下架的圆环鸽编号:");
        int pNo = sc.nextInt();

        boolean exists = pigeons.stream().anyMatch(p->p.getpNo()==pNo);

        if(!exists){
            System.out.println("未找到编号:"+pNo+",请尝试其他编号");
            return;
        }

        pigeons.removeIf(p->p.getpNo()==pNo);
        LmFileHelper.writePigeons(pigeons);

        show();
    }

    private static void add(Scanner sc) throws IOException,ClassNotFoundException {
        ArrayList<Pigeon> pigeons = LmFileHelper.readPigeons();
        if(pigeons==null || pigeons.isEmpty()){
            pigeons = new ArrayList<>();
        }

        System.out.println("请输入圆环鸽编号:");
        int pNo = sc.nextInt();
        System.out.println("请输入圆环鸽名称:");
        String pName = sc.next();
        System.out.println("请输入圆环鸽鸽主名称:");
        String pAuthor = sc.next();

        Pigeon pigeon = new Pigeon(pNo,pName,pAuthor);
        pigeons.add(pigeon);

        //保存到文件数据库
        LmFileHelper.writePigeons(pigeons);

        show();
    }

    private static void show() throws IOException,ClassNotFoundException {
        ArrayList<Pigeon> pigeons = LmFileHelper.readPigeons();
        if(pigeons==null || pigeons.isEmpty()){
            System.out.println("展厅暂时没有可售卖的圆环鸽,请先上架!!!");
            return;
        }
        for(Pigeon p:pigeons){
            System.out.println(p);
        }
    }

    private static void welcome(){
        System.out.println("欢迎来到芷儿凤凰鸽舍展厅==============");
        System.out.println("1.展示圆环鸽列表");
        System.out.println("2.上架圆环鸽");
        System.out.println("3.下架圆环鸽");
        System.out.println("4.退出展厅");
    }

}